package cn.lds.j368.dsbank.configuration;

import cn.lds.j368.dsbank.service.EmpRoleService;
import cn.lds.j368.dsbank.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private EmployeeService employeeService;


//    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/","/emp/login","/css/**","/js/**","/img/**").permitAll()
                .antMatchers("/customer/**").hasRole("CUSTOMER_MANAGE")
                .antMatchers("/emp/**").hasRole("EMP_MANAGE")
                .antMatchers("/loan/**").hasRole("CUSTOMER_MANAGE")
                .and().formLogin().loginPage("/emp/login")
                .loginProcessingUrl("/emp/do_login")
                .usernameParameter("empUsername")
                .passwordParameter("empPassword")
                .failureUrl("/emp/login?err=true")
                .and()
                .logout()
                .invalidateHttpSession(true)
                .logoutUrl("/logout")
                .logoutSuccessUrl("/")
                .and().authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .csrf()
                .disable();
    }

    /**
     * SpringSecurity 提供的Bcrypt加密工具
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(employeeService).passwordEncoder(passwordEncoder());
    }
}
